package com.xwp.exception;

import com.xwp.enums.GlobalExceptionCode;
import com.xwp.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult customException(Exception e) {
        e.printStackTrace();
        log.error("处理自定义全局异常，异常类型为：GlobalCustomException，错误信息：", e.getMessage());
        return JSONResult.error(GlobalExceptionCode.ERROR);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult customException(GlobalCustomException e) {
        e.printStackTrace();
        log.error("处理自定义全局异常，异常类型为：GlobalCustomException，错误信息：", e.getMessage());
//        return JSONResult.error(GlobalExceptionCode.PARAM_IS_NULL_ERROR.getMessage(), GlobalExceptionCode.PARAM_IS_NULL_ERROR.getCode());
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult customException(MethodArgumentNotValidException e) {
        e.printStackTrace();
        log.error("处理自定义全局异常，异常类型为：GlobalCustomException，错误信息：", e.getMessage());
//        return JSONResult.error(GlobalExceptionCode.PARAM_IS_NULL_ERROR.getMessage(), GlobalExceptionCode.PARAM_IS_NULL_ERROR.getCode());
        StringBuilder stringBuilder = new StringBuilder();
        e.getBindingResult().getAllErrors().forEach(obj -> {
            stringBuilder.append(obj.getDefaultMessage()).append(",");
        });
        return JSONResult.error(stringBuilder.toString(), "-1000");
    }

}